package com.reger.l2cache.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisConnectionUtils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class RedisPublish {

	private static final Logger log = LoggerFactory.getLogger(RedisPublish.class);

	protected static final ObjectMapper objectMapper = new ObjectMapper();
	protected static RedisConnectionFactory connectionFactory;
	static {
		objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
	}

	public static void convertAndSend(String channelName, Object... messages) {
		if (connectionFactory == null) {
			log.warn("没有初始化RedisConnectionFactory,无法发布消息 channelName={}", channelName);
			return;
		}
		RedisConnection connection = null;
		try {
			connection = RedisConnectionUtils.getConnection(connectionFactory);
			connection.openPipeline();
			try {
				for (Object message : messages) {
					if (message == null) {
						log.info("消息为空，无法发布消息 channelName={}", channelName);
						continue;
					}
					if (message instanceof String) {
						connection.publish(channelName.getBytes(), ((String) message).getBytes());
					} else if (message instanceof Number) {
						connection.publish(channelName.getBytes(), (String.valueOf(message)).getBytes());
					} else if (message instanceof byte[]) {
						connection.publish(channelName.getBytes(), (byte[]) message);
					} else {
						connection.publish(channelName.getBytes(), objectMapper.writeValueAsBytes(message));
					}
				}
			} finally {
				connection.closePipeline();
			}
		} catch (JsonProcessingException e) {
			throw new RuntimeException(e);
		} finally {
			RedisConnectionUtils.releaseConnection(connection, connectionFactory);
		}
	}
}
